from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from app.schemas.student import Student, StudentCreate, StudentUpdate
from app.crud import student as student_crud
from app.api.deps import get_db_session

router = APIRouter()

@router.get("/", response_model=List[Student])
async def read_students(
    skip: int = 0, 
    limit: int = 100, 
    db: AsyncSession = Depends(get_db_session)
):
    students = await student_crud.get_students(db, skip=skip, limit=limit)
    return students

@router.post("/", response_model=Student, status_code=201)
async def create_student(
    student: StudentCreate, 
    db: AsyncSession = Depends(get_db_session)
):
    db_student = await student_crud.get_student_by_email(db, email=student.email)
    if db_student:
        raise HTTPException(status_code=400, detail="Email already registered")
    return await student_crud.create_student(db=db, student=student)

@router.get("/{student_id}", response_model=Student)
async def read_student(
    student_id: int, 
    db: AsyncSession = Depends(get_db_session)
):
    db_student = await student_crud.get_student(db, student_id=student_id)
    if db_student is None:
        raise HTTPException(status_code=404, detail="Student not found")
    return db_student

@router.put("/{student_id}", response_model=Student)
async def update_student(
    student_id: int, 
    student: StudentUpdate, 
    db: AsyncSession = Depends(get_db_session)
):
    db_student = await student_crud.get_student(db, student_id=student_id)
    if db_student is None:
        raise HTTPException(status_code=404, detail="Student not found")
    
    # 检查邮箱是否已被其他学生使用
    if student.email:
        existing_student = await student_crud.get_student_by_email(db, email=student.email)
        if existing_student and existing_student.id != student_id:
            raise HTTPException(status_code=400, detail="Email already registered")
    
    return await student_crud.update_student(db=db, student_id=student_id, student_update=student)

@router.delete("/{student_id}", response_model=Student)
async def delete_student(
    student_id: int, 
    db: AsyncSession = Depends(get_db_session)
):
    db_student = await student_crud.get_student(db, student_id=student_id)
    if db_student is None:
        raise HTTPException(status_code=404, detail="Student not found")
    return await student_crud.delete_student(db=db, student_id=student_id)